package com.qf.controller;

import com.qf.pojo.PageBean;
import com.qf.pojo.Product;
import com.qf.service.ProductService;
import com.qf.service.impl.ProductServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 商品后端的访问地址
 */
@WebServlet("/product")
public class ProductServlet extends BaseServlet {

    /**
     * 根据商品pid获取指定的商品的功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getProduct(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //${pageContext.request.contextPath}/product?methodName=getProduct&pid=${p.pid}
        String pid = request.getParameter("pid");
        System.out.println(pid);

        //调用业务接口
        ProductService productService = new ProductServiceImpl() ;
        Product product = productService.getProduct(pid);
        if(product !=null){
            request.setAttribute("product",product) ;
        }
        //请求转发到商品详情页
        request.getRequestDispatcher("/jsp/product_info.jsp").forward(request,response);
    }

    /**
     * 点击分类信息获取商品分页数据
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getProductByPage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //${pageContext.request.contextPath}/product?methodName=getProductByPage&curPage=1&pSize=12&cid="+this.cid+"'
        //1)接收参数
        String curPage = request.getParameter("curPage");
        String pSize = request.getParameter("pSize");
        String cid = request.getParameter("cid") ;
        //2)将curPage/pSize转换成int
        int currentPage = Integer.parseInt(curPage);
        int pageSize = Integer.parseInt(pSize);

        //3)调用商品业务接口
        ProductService productService = new ProductServiceImpl() ;
        PageBean<Product> pb = productService.getProductsByPage(currentPage, pageSize, cid);
        System.out.println(pb) ;

        //4)存储在request域中
        request.setAttribute("pb",pb) ;
        //5)请求转发到jsp/product_list.jsp
        request.getRequestDispatcher("/jsp/product_list.jsp").forward(request,response);
    }
}
